package com.yunbao.hujin.myoss;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.common.utils.BinaryUtil;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

import okhttp3.Request;

/**
 * 压缩图片上传到 阿里云OSS
 */

public class PhotoImageController {

    private Context context;

    public PhotoImageController(Context context) {
        this.context = context;
    }


    /**
     * 阿里云OSS
     * 访问服务器接口，获取必要的信息
     */
    public void getOssInfoFromServer(final String filePath) {
//        String url = "http://192.168.31.101:8085/sysstatic/ossinfo";
//
//        OkHttpUtils.asyncRequest("POST", url, new HashMap<String, String>(), new OkHttpUtils.ResultCallback<String>() {
//            @Override
//            public void onResponse(String response) {
//                Log.i("tag", "photoImageController-onResponse=" + response);
//                initOss(filePath, response);
//            }
//
//            @Override
//            public void onError(Request request, Exception e) {
//                Log.i("tag", "photoImageController-onError=" + request.toString() + "," + e.getMessage());
//            }
//        });
        Log.e("Tag-filePath", filePath);
        initOss(filePath);
    }


    // 配置OSS
    private void initOss(String filePath) {
        String endPoint = "************";               //自己的endPoint
        String bucketName = "*****";
        String secretKey = "******";
        String accessKey = "**********";
        String objectName = "***/";              //文件夹名字随便

        //初始化oss    //ACCESS_ID,ACCESS_KEY是在阿里云申请的
        // String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        OSSCredentialProvider provider = new OSSPlainTextAKSKCredentialProvider(accessKey, secretKey);
        //OSSCredentialProvider provider = new OSSStsTokenCredentialProvider(accessKey,secretKey,"<StsToken.SecurityToken>");

        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(10 * 1000);       // 连接超时，默认10秒
        conf.setSocketTimeout(10 * 1000);           // socket超时，默认10秒
        conf.setMaxConcurrentRequest(5);            // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2);                   // 失败后最大重试次数，默认2次

//        OSSLog.enableLog();//调用此方法即可开启日志

//        OSSClient oss = new OSSClient(context, endPoint, provider);
        OSSClient oss = new OSSClient(context, endPoint, provider, conf);
        try {
            uploadFile(oss, bucketName, objectName, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传文件
     */
    private void uploadFile(OSS oss, String bucketName, String objectName, String filePath) throws IOException {
//        objectKey其实就是服务器上的路径，即目录+文件名,通过这个名字指定上传和下载的文件
        String fileName[] = filePath.split("/");
        PutObjectRequest put = new PutObjectRequest(bucketName, objectName + fileName[fileName.length - 1], filePath);

        // 文件元信息的设置是可选的
        // 指定数据类型，没有指定会自动根据后缀名判断
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpeg");
        metadata.setContentMD5(BinaryUtil.calculateBase64Md5(filePath)); // 校验MD5

        put.setMetadata(metadata);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest putObjectRequest, long currentSize, long totalSize) {
                // 在这里可以实现进度条展现功能
//                Log.e("Tag-PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
//                Log.d("ETag", putObjectResult.getETag());
//                Log.d("RequestId", putObjectResult.getRequestId());
                Log.e("Tag--------","putObjectRequest.getObjectKey()=" + putObjectRequest.getObjectKey());
                String imageUrl = "http://*********" + putObjectRequest.getObjectKey();
//                Picasso.with(PersonalInfoEditActivity.this).load(headUrl).into(personalHeadIcon);
            }

            @Override
            public void onFailure(PutObjectRequest putObjectRequest, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("tag", serviceException.getErrorCode());
                    Log.e("tag", serviceException.getRequestId());
                    Log.e("tag", serviceException.getHostId());
                    Log.e("tag", serviceException.getRawMessage());
                }
                Toast.makeText(context, "图片上传失败，请重新上传", Toast.LENGTH_SHORT).show();
                return;
            }
        });
    }


    /**
     * 将选取的本地图片压缩后再次保存到本地
     */
    public String saveBitmap(Bitmap mBitmap) {
        File filePic;
        String savePath = context.getApplicationContext().getFilesDir().getAbsolutePath();
        String uuidFile = UUID.randomUUID().toString();

        try {
            filePic = new File(savePath + uuidFile + ".jpg");
            Log.e("Tagsave--","path=" + savePath + uuidFile + ".jpg");
            if (!filePic.exists()) {
                filePic.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }


}
